﻿using System.Collections.Generic;
using System.Linq;
using StockFinder.Model;

namespace StockFinder.Indicators.Day.HighLowPrice
{
    /// <summary>
    /// Determines the simple moving average average Trading Range Volatility
    /// </summary>
    public class SimpleMovingAverageTradingRangeHighLowPriceDayIndicator : BaseDayIndicator
    {        
        public SimpleMovingAverageTradingRangeHighLowPriceDayIndicator(int lookbackPeriod, string indicatorName)
            : base(lookbackPeriod, indicatorName)
        {
        }

        public override void ApplyIndicator(List<DailyPrice> prices)
        {
            if (!Initialize(prices)) return;

            var orderedPrices = prices.OrderBy(p => p.PriceDate);
            DailyPrice currentPrice;

            IEnumerable<DailyPrice> skippedPrices;
            IEnumerable<DailyPrice> takenPrices;            

            //start from 50
            for (var i = (LookbackPeriod - 1); i < orderedPrices.Count(); i++)
            {
                currentPrice = orderedPrices.ElementAt(i);

                var numberToSkip = (i + 1) - LookbackPeriod;

                skippedPrices = orderedPrices.Skip(numberToSkip);

                takenPrices = skippedPrices.Take(LookbackPeriod);

                currentPrice.DayIndicators[IndicatorName] = takenPrices.Average(p => ((p.AdjustedHigh - p.AdjustedLow) / p.AdjustedLow) * 100);
            }
        }        
    }
}
